import datetime
import ssl

from alipay import AliPay
from celery import task
from django.db.models import F

from it_alipay.models import PayOrder
from users.models import UserProfile
from utils.dateutil import get_today_month


def get_ali_object():
    # 沙箱环境地址：https://openhome.alipay.com/platform/appDaily.htm?tab=info
    app_id = "2018121762553950"  #  APPID （正式应用）

    # 支付完成后，支付偷偷向这里地址发送一个post请求，识别公网IP,如果是 192.168.20.13局域网IP ,支付宝找不到，def page2() 接收不到这个请求
    notify_url = "http://imagethinking.semyes.cn/pay_finish_page/"
    # notify_url = "http://127.0.0.1:8000/pay_finish_page/"

    # 支付完成后，跳转的地址。
    return_url = "http://imagethinking.semyes.cn/pay_finish_page/"
    # return_url = "http://127.0.0.1:8000/pay_finish_page/"

    merchant_private_key_path = "keys/app_private_2048.txt" # 应用私钥
    alipay_public_key_path = "keys/alipay_public_2048.txt"  # 支付宝公钥

    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,
        app_private_key_path=merchant_private_key_path,
        alipay_public_key_path=alipay_public_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥
        # debug=True,  # 默认False,
    )
    return alipay


@task
def check_pay_order():
    alipay = get_ali_object()

    # 最近三天
    now = datetime.datetime.now()
    start = now + datetime.timedelta(days=-3)

    pay_orders = PayOrder.objects.filter(status=0, start_time__gte=start)

    if pay_orders.count() > 0:
        for pay_order in pay_orders:
            if pay_order.status == 0:
                # 调用alipay工具查询支付结果，判断此订单是否已支付
                # https://docs.open.alipay.com/api_1/alipay.trade.query
                ssl._create_default_https_context = ssl._create_unverified_context
                response = alipay.api_alipay_trade_query(pay_order.out_trade_no)  # response是一个字典

                # 判断支付结果
                code = response.get("code")  # 支付宝接口调用成功或者错误的标志
                trade_no = response.get("trade_no")  # 支付宝交易号
                buyer_user_id = response.get("buyer_user_id")  # 买家在支付宝的用户id
                total_amount = response.get("total_amount")  # 交易的订单金额，单位为元，两位小数。
                trade_status = response.get("trade_status")  # 用户支付的情况，交易状态
                send_pay_date = response.get("send_pay_date")  # 本次交易打款给卖家的时间

                if code == "10000" and trade_status == "TRADE_SUCCESS":

                    one_more_month = get_today_month(send_pay_date, 1)

                    try:
                        # 更新订单信息
                        PayOrder.objects.filter(user_id=pay_order.user_id,
                                                out_trade_no=pay_order.out_trade_no)\
                            .update(total_amount=total_amount,
                                trade_no=trade_no,
                                seller_id=buyer_user_id,
                                status=1,
                                start_time=send_pay_date,
                                finish_time=one_more_month
                            )

                        # 更新用户信息
                        user = UserProfile.objects.filter(id=pay_order.user_id)
                        if user[0].pay_times >= 1:
                            user.update(vip=1,
                                        renewal_time=send_pay_date,
                                        finish_time=one_more_month,
                                        pay_times=F("pay_times") + 1
                                        )
                        else:
                            user.update(vip=1,
                                        start_time=send_pay_date,
                                        renewal_time=send_pay_date,  # 续期时间
                                        finish_time=one_more_month,
                                        pay_times=F("pay_times") + 1
                                        )
                    except Exception as e:
                        print(e)